// utils/invoiceParser.js
const CryptoJS = require('crypto-js');/* 

// 或根据您的环境使用
import CryptoJS from 'crypto-js'; */

const SECRET_ID = 'AKIDaM0VoupaAWfdVBj7ITwEbt1EboojP6bt';
const SECRET_KEY = '94lFVXLzPbcMyUp02ua4NUQvFLDrHcjc';
const API_URL = 'https://yuanqi.tencent.com/api/v1/chat/completions';
const ASSISTANT_ID = 'file_parser';
const SERVICE = 'yuanqi'; // 服务名
const REGION = 'ap-guangzhou'; // 地域代码
const SOURCE = 'YourAppName'; // 替换为您的应用名称

// 生成腾讯云API所需签名
const generateAuthorization = () => {
  const timestamp = Math.floor(Date.now() / 1000);
  const date = new Date(timestamp * 1000).toISOString().split('T')[0].replace(/-/g, '');
  
  // 生成规范请求
  const hashedCanonicalRequest = CryptoJS.SHA256([
    'POST',
    '/api/v1/chat/completions',
    '',
    `x-tc-timestamp:${timestamp}`,
    `x-source:${SOURCE}`,
    '',
    'x-source;x-tc-timestamp',
    '' // 请求体为空，实际请求体在后续步骤处理
  ].join('\n')).toString(CryptoJS.enc.Hex);
  
  // 生成待签名字符串
  const credentialScope = `${date}/${REGION}/${service}/tc3_request`;
  const stringToSign = [
    'TC3-HMAC-SHA256',
    timestamp,
    credentialScope,
    hashedCanonicalRequest
  ].join('\n');
  
  // 生成签名
  const sign = (message, key) => 
    CryptoJS.HmacSHA256(message, key).toString(CryptoJS.enc.Hex);
  
  // 计算签名密钥
  const secretDate = sign(date, 'TC3' + SECRET_KEY);
  const secretRegion = sign(REGION, secretDate);
  const secretService = sign(SERVICE, secretRegion);
  const signingKey = sign('tc3_request', secretService);
  
  const signature = sign(stringToSign, signingKey);
  
  // 生成Authorization头
  return `TC3-HMAC-SHA256 Credential=${SECRET_ID}/${credentialScope}, ` +
         `SignedHeaders=x-source;x-tc-timestamp, ` +
         `Signature=${signature}`;
};

// 解析发票
export const parseInvoice = async (filePath) => {
  try {
    uni.showLoading({ title: '解析中...', mask: true });
    
    // 获取文件扩展名
    const fileExt = filePath.split('.').pop().toLowerCase();
    const supportedFormats = ['jpg', 'jpeg', 'png', 'pdf'];
    
    if (!supportedFormats.includes(fileExt)) {
      throw new Error(`只支持 ${supportedFormats.join('、')} 格式的文件`);
    }
    
    // 文件转Base64
    const base64Data = await new Promise((resolve, reject) => {
      uni.getFileSystemManager().readFile({
        filePath,
        encoding: 'base64',
        success: res => resolve(res.data),
        fail: err => reject(err)
      });
    });
    
    // 创建正确的请求体
    const requestBody = {
      assistant_id: ASSISTANT_ID,
      stream: false,
      messages: [{
        role: "user",
        content: JSON.stringify([
          { type: "file", file: base64Data, file_type: fileExt }
        ])
      }]
    };
    
    const timestamp = Math.floor(Date.now() / 1000);
    
    // 发送API请求
    const res = await uni.request({
      url: API_URL,
      method: 'POST',
      header: {
        'Authorization': generateAuthorization(),
        'Content-Type': 'application/json',
        'X-TC-Timestamp': timestamp.toString(),
        'X-Source': SOURCE
      },
      data: JSON.stringify(requestBody),
      timeout: 30000
    });
    
    // 处理响应
    if (res.statusCode === 200) {
      try {
        return JSON.parse(res.data).data; // 返回解析结果
      } catch (e) {
        throw new Error('API响应解析失败');
      }
    } else {
      console.error('API返回错误:', res);
      throw new Error(`解析失败 (状态码: ${res.statusCode})`);
    }
  } catch (error) {
    console.error('发票解析失败:', error);
    uni.showToast({
      title: error.message || '解析失败',
      icon: 'none',
      duration: 3000
    });
    return null;
  } finally {
    uni.hideLoading();
  }
};